import csv
import io
import chardet
from flask import Blueprint, jsonify, request
from flask_jwt_extended import jwt_required
from libs.conn import *
from libs.utils import *

tasks_bp = Blueprint('tasks', __name__)

@tasks_bp.route('/api/get_tasks')
@jwt_required()
def get_tasks():
    client_id = request.args.get('client_id')
    task_name = request.args.get('task_name')
    task_type = request.args.get('task_type')
    task_enable = request.args.get('task_enable')
    task_result = request.args.get('task_result')
    page_size = int(request.args.get('page_size'))
    page_current = int(request.args.get('page_current'))
    params = []
    sql = "FROM tasks WHERE 1=1"
    if client_id != None:
        sql += " AND client_id = ?"
        params.append(client_id)
    if task_name != None:
        sql += " AND task_name like ?"
        params.append("%"+task_name+"%")
    if task_type != None:
        sql += " AND task_type = ?"
        params.append(task_type)
    if task_enable != None:
        sql += " AND task_enable = ?"
        params.append(task_enable)
    if task_result != None:
        sql += " AND task_result = ?"
        params.append(task_result)
    offset = (page_current - 1) * page_size
    rows = fetchall('SELECT * ' + sql + " LIMIT ? OFFSET ?", tuple(params + [page_size, offset]))
    total_count = fetchvalue('SELECT COUNT(*) ' + sql, tuple(params))
    return { 'status': 'ok', 'data': rows, 'page_total': total_count }

@tasks_bp.route('/api/get_client_tasks', methods=['POST'])
@jwt_required()
def get_client_tasks():
    client_id = request.json.get('client_id')
    rows = fetchall('SELECT * FROM tasks WHERE client_id = ?', (client_id,))
    return { 'status': 'ok', 'data': rows }

@tasks_bp.route('/api/add_task', methods=['POST'])
@jwt_required()
def add_task():
    client_id = request.json.get('client_id')
    task_name = request.json.get('task_name')
    task_type = request.json.get('task_type')
    client_ip = request.json.get('client_ip')
    client_port = int(request.json.get('client_port'))
    task_id = execute("INSERT INTO tasks (client_id, task_name, task_type, client_ip, client_port) VALUES (?, ?, ?, ?, ?)", (client_id, task_name, task_type, client_ip, client_port))
    return { 'status': 'ok', 'data': task_id }

# 批量添加任务
@tasks_bp.route('/api/add_batch_task', methods=['POST'])
@jwt_required()
def add_batch_task():
    client_ids = request.json.get('client_ids')
    task_name = request.json.get('task_name')
    task_type = request.json.get('task_type')
    client_port = int(request.json.get('client_port'))
    task_enable = int(request.json.get('task_enable'))
    success_count = 0
    conn, cursor = create_conn()
    try:
        for client_id in client_ids:
            cursor.execute('SELECT client_ip FROM clients WHERE client_id = ?', (client_id,))
            row = cursor.fetchone()
            if row == None:
                continue
            client_ip = row[0]
            if client_ip == None or client_ip == '':
                continue
            cursor.execute("INSERT INTO tasks (client_id, task_name, task_type, client_ip, client_port, task_enable) VALUES (?, ?, ?, ?, ?, ?)", (client_id, task_name, task_type, client_ip, client_port, task_enable))
            if cursor.rowcount > 0:
                success_count += 1
        conn.commit()
    except Exception as e:
        print(f"Error: {e}")
        conn.rollback()
    finally:
        cursor.close()
    return { 'status': 'ok', 'data': success_count }

@tasks_bp.route('/api/update_task', methods=['POST'])
@jwt_required()
def update_task():
    task_id = request.json.get('task_id')
    task_name = request.json.get('task_name')
    task_type = request.json.get('task_type')
    client_ip = request.json.get('client_ip')
    client_port = int(request.json.get('client_port'))
    if client_ip != None and client_ip != '' and is_valid_ip_or_domain(client_ip) == False:
        return { 'status': 'error', 'data': 'IP地址或域名格式不正确' }
    execute("UPDATE tasks SET task_name = ?, task_type = ?, client_ip = ?, client_port = ? WHERE task_id = ?", (task_name, task_type, client_ip, client_port, task_id))
    return { 'status': 'ok', 'data': 'success' }

@tasks_bp.route('/api/delete_task', methods=['POST'])
@jwt_required()
def delete_task():
    task_id = request.json.get('task_id')
    execute("DELETE FROM tasks WHERE task_id = ?", (task_id,))
    return { 'status': 'ok', 'data': 'success' }

@tasks_bp.route('/api/task_enable', methods=['POST'])
@jwt_required()
def task_enable():
    task_id = request.json.get('task_id')
    task_enable = int(request.json.get('task_enable'))
    execute("UPDATE tasks SET task_enable = ? WHERE task_id = ?", (task_enable, task_id))
    return { 'status': 'ok', 'data': 'success' }

